package hw.txtreader.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.bifan.txtreaderlib.main.TxtConfig;
import com.bifan.txtreaderlib.ui.HwTxtPlayActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import hw.txtreader.R;
import hw.txtreader.activity.LoginActivity;
import hw.txtreader.activity.RegisterActivity;
import hw.txtreader.adapter.BookAdapter;
import hw.txtreader.base.BaseFragment;
import hw.txtreader.databinding.FragmentThirdBinding;
import hw.txtreader.listener.OnItemClickListener;
import hw.txtreader.utils.LogUtil;
import hw.txtreader.utils.SPUtil;

/**
 * 直接去阅读的方法
 * HwTxtPlayActivity.loadTxtFile(getActivity(), FilePath);
 * <p>
 * 书籍缓存key: module_book_list
 */
public class ThirdFragment extends BaseFragment {

    private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 0x01;
    private String FilePath = Environment.getExternalStorageDirectory() + "/test4.txt";
    private Boolean Permit = false;
    FragmentThirdBinding binding;
    List<String> bookPaths = new ArrayList<>();
    BookAdapter adapter;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(LayoutInflater.from(getActivity()), R.layout.fragment_third, null, false);
        binding.setFragment(this);

        initView();
        return binding.getRoot();
    }

    private void initView() {

        Type listType = new TypeToken<List<String>>() {
        }.getType();
        String spRes = SPUtil.getString(getActivity(), "module_book_list", "");
        if (spRes != null) {
            if (!TextUtils.isEmpty(spRes)) {
                Gson gson = new Gson();
                bookPaths = gson.fromJson(spRes, listType);
            }
        }

        binding.rlModule.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        binding.rlModule.setItemAnimator(new DefaultItemAnimator());
        adapter = new BookAdapter(getActivity(), bookPaths);
        binding.rlModule.setAdapter(adapter);
        adapter.setOnItemClickLitener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                TxtConfig.saveIsOnVerticalPageMode(getActivity(), false);
                if (TextUtils.isEmpty(bookPaths.get(position)) || !(new File(bookPaths.get(position))).exists()) {
                    toast("文件不存在");
                } else {
                    HwTxtPlayActivity.loadTxtFile(getActivity(), bookPaths.get(position));
                }
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });

        //添加书籍
        binding.tvModuleAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CheckPermission()) {
                    Permit = true;
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("text/plain");//设置类型
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    startActivityForResult(intent, 3);
                } else {
                    Toast.makeText(getActivity(), "请设置读写内存权限", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    String path;
    boolean isCon = false;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {//是否选择，没选择就不会继续
            Uri uri = data.getData();//得到uri，后面就是将uri转化成file的过程。
            String[] pros = {MediaStore.Files.FileColumns.DATA};
            try {
                Cursor cursor = getActivity().managedQuery(uri, pros, null, null, null);
                int actual_txt_column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                path = cursor.getString(actual_txt_column_index);
                LogUtil.e("获取到路径-->" + path);
                if (!TextUtils.isEmpty(path)) {
                    isCon = false;
                    for (String str : bookPaths) {
                        if (str.contains(path)) {
                            isCon = true;
                        }
                    }
                    if (!isCon) {
                        bookPaths.add(path);
                        adapter.notifyDataSetChanged();
                    } else {
                        Toast.makeText(getActivity(), "书籍" + path + "已收录", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
            } catch (Exception e) {
                toast("选择出错了");
            }
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        if (bookPaths.size() > 0) {
            Gson sGson = new Gson();
            String data = sGson.toJson(bookPaths);
            SPUtil.putString(getActivity(), "module_book_list", data);
        }
    }

    private Boolean CheckPermission() {
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Permit = true;

            } else {
                // Permission Denied
                Toast.makeText(getActivity(), "Permission Denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private Toast t;

    private void toast(String msg) {
        if (t != null) {
            t.cancel();
        }
        t = Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT);
        t.show();
    }

}